package com.eportal.action.background;


import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.PayOrder;
import com.eportal.domain.PayQrcode;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TLock;
import com.eportal.domain.ThridpayBill;
import com.eportal.domain.TpayWalletlst;
import com.eportal.domain.TuserWallet;
import com.eportal.service.PayOrderService;
import com.eportal.service.PayQrcodeService;
import com.eportal.service.PayWalletlstService;
import com.eportal.service.RedEnvService;
import com.eportal.service.ThridpayBillService;
import com.eportal.service.UserWalletService;
import com.eportal.util.Config;
import com.eportal.util.DateUtils;
import com.eportal.util.HomePageConfig;
import com.eportal.util.HttpHelper;
import com.eportal.util.HttpUtil;
import com.eportal.util.MD5;
import com.eportal.util.MdExpiringMap;
import com.eportal.util.SmsHelper;
import com.eportal.util.VerifyCodeHelper;
import com.eportal.util.WebUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

import net.sf.json.JSONObject;

/**
 * 二维码收款
 * @author wangk
 *
 */
public class PayQrcodeAction extends BaseAction implements ModelDriven<PayQrcode> {
	
 
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(PayQrcodeAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();

    @Autowired
    private UserWalletService  tUserWalletService;
    
    @Autowired
    private ThridpayBillService thridpayBillService;
    
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private RedEnvService redEnvService;
    
    @Autowired
    private PayWalletlstService payWalletlstService;
    @Autowired
    private PayQrcodeService payQrcodeService;
    
    
    /**
     * 处理菜单
     */
    void doMenu(){
    	String homePageConfig = HomePageConfig.USER_WALLET;
    	String[] str = homePageConfig.split(",");
		getRequest().setAttribute("mpid", Integer.parseInt(str[0]));
    	getSession().setAttribute("mpid", Integer.parseInt(str[0]));
    	String act = getRequest().getParameter("act");
    	if(act==null){
    		act="1";
    	}
    	getRequest().setAttribute("act", act);
    }
    
    
    public String addView(){
    	String msg =null;
    	try{
    		doMenu();
        	Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		getRequest().setAttribute("msg", "不支持访问该页面");
        		return "exception";
        	}
        	PayQrcode payQrcode = payQrcodeService.getByWid(wallet.getWid());
        	if(payQrcode!=null){
        		getRequest().setAttribute("sid", payQrcode.getSid());
            	getRequest().setAttribute("cname", payQrcode.getCname());	
            	getRequest().setAttribute("url",getPayUrl(payQrcode.getSid().toString(), getRequest()));
        	}
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	getRequest().setAttribute("msg", msg);
    	return SUCCESS;
    }
    
    public static String getPayUrl(String sid,HttpServletRequest req){
    	return WebUtil.getReqPreUrl(req)+"u/d?i="+sid;
    }
    
    public String payView(){
    	String msg =null;
    	try{
    		String sid = getRequest().getParameter("i");
    		PayQrcode payQrcode = payQrcodeService.get(Long.valueOf(sid));
    		getRequest().setAttribute("cname", payQrcode.getCname());
    		getRequest().setAttribute("sid", sid);
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	return SUCCESS;
    }
    
    public String payResult(){
    	String msg =null;
    	try{
    		String payid = getRequest().getParameter("payid");
    		ThridpayBill bill = thridpayBillService.getByPayId(payid);
    		if("0".equals(bill.getPstate())){
    			getRequest().setAttribute("pstate_", "支付成功");
    		}else{
    			getRequest().setAttribute("pstate_", "支付中");
    		}
    		getRequest().setAttribute("amount", bill.getAmount());
    		getRequest().setAttribute("did",bill.getDid());
    		getRequest().setAttribute("time", DateUtils.formatDatetime(new Date(bill.getCreatetime().getTime())));
    		
    	}catch(Exception e){
    		log.error(this, e);
    	}
    	return SUCCESS;
    }
    
    public void pay(){
    	try{
    		String sid = getRequest().getParameter("sid");
    		PayQrcode payQrcode = payQrcodeService.get(Long.valueOf(sid));
    		
    		String amount = getRequest().getParameter("amount");
    		String memo = getRequest().getParameter("memo");
    		 /*      		PayOrder payOrder = new PayOrder();
 		payOrder.setAmount(new BigDecimal(amount));
    		payOrder.setCtime(new Timestamp(System.currentTimeMillis()));
    		payOrder.setCname("二维码收款");
    		payOrder.setCusername("SYSTEM");
    		payOrder.setUserMemo(memo);
    		payOrder.setPstate("1");
    		payOrder.setWid(payQrcode.getWid());
    		payOrder.setDepartid("10001");
    		payOrder.setUserType("1");
    		payOrder.setOrderRelate("R0002");
    		payOrderService.save(payOrder);
    		payOrder.setReturnUrl(WebUtil.getReqPreUrl(getRequest())+"admin/payQrcode_payResult.action?orderId="+payOrder.getSid());
    		payOrderService.update(payOrder);
    		*/
    		Map map = new HashMap();
			map.put("apiId", "Api_Wallet_Pay_Wap_Request");
			map.put("wid", payQrcode.getWid());
			map.put("departid", "10001");
			map.put("amount", amount);
			map.put("subject","向"+payQrcode.getCname()+"转账");
			map.put("returnUrl", WebUtil.getReqPreUrl(getRequest())+"admin/payQrcode_payResult.action?payid=${payid}");
			map.put("clientIp", WebUtil.getIpAddr(getRequest()));
			//map.put("orderId", payOrder.getSid());
			Map m = new HashMap();
			m.put("requestjson", JSONObject.fromObject(map).toString());
			String str = HttpHelper.doPostForm(m,Config.PAY_SERVICE_URL+"/service/ldo");
			if("0".equals(getResultCode4PayService(str))){
				Map obj = (Map)getObj4PayService(str);
				if("0".equals(obj.get("code"))){
					String url =  (String)obj.get("url");
					result.put("url", url);
					result.put("code", 1);
					//responseBody(result);
					responseBody(url);
			    	return;
				}else{
					result.put("code", 0);
    	    		result.put("msg", "支付失败");
				}
			}else if("10000".equals(getResultCode4PayService(str))){
				result.put("code", 0);
	    		result.put("msg", getResultMessage4PayService(str));
			}else{
				result.put("code", 0);
	    		result.put("msg", "支付失败");
			}
    	}catch(Exception e){
    		result.put("code", "0");
    		result.put("msg", "操作失败");
    		log.error(this, e);
    	}
    	responseBody(result);
    	return;
    }
    
    static String getResultCode4PayService(String result){
    	return JSONObject.fromObject(result).getJSONObject("status").getString("resultcode");
    }
    
    static String getResultMessage4PayService(String result){
    	return JSONObject.fromObject(result).getJSONObject("status").getString("resultmssage");
    }
    
    static Object getObj4PayService(String result){
    	return JSONObject.toBean(JSONObject.fromObject(result).getJSONObject("pageList"), Map.class);
    }
    
    
    public void add(){
    	String msg =null;
    	try{
        	Sysopt  user = (Sysopt)getSession().getAttribute("user");
        	TuserWallet wallet =  tUserWalletService.getOrcreateWallet(user.getrLevel(),user.getAgtCode(),user.getCommunityId());
        	if(wallet==null){
        		result.put("code", "0");
        		result.put("msg", "无法获取零钱");
        		responseBody(result);
        		return;
        	}
        	String cname = getRequest().getParameter("cname");
        	PayQrcode payQrcode = payQrcodeService.getByWid(wallet.getWid());
        	if(payQrcode!=null){
        		payQrcode.setCname(cname);
        		payQrcodeService.update(payQrcode);
        	}else{
        		payQrcode = new PayQrcode();
        		payQrcode.setCname(cname);
        		payQrcode.setAgtcode(user.getAgtCode());
        		payQrcode.setCommunityid(user.getcName());
        		payQrcode.setCtime(new Timestamp(System.currentTimeMillis()));
        		payQrcode.setWid(wallet.getWid().toString());
        		payQrcode.setCusername(user.getSid().toString());
        		payQrcodeService.add(payQrcode);
        	}
        	result.put("code", "1");
        	result.put("url", getPayUrl(payQrcode.getSid().toString(), getRequest()));
    	}catch(Exception e){
    		result.put("code", "0");
    		result.put("msg", "操作失败");
    		log.error(this, e);
    	}
    	responseBody(result);
    	return;
    }
	
    
	@Override
	public PayQrcode getModel() {
		// TODO Auto-generated method stub
		return null;
	}

    
    
    
    
}
